<template>
  <div class="exam-editor-container" @click="handleClickOutside">
    <div>
      <!-- 试卷头显示区域 -->
      <header class="paper-header" v-if="showPaperHeader &&paperHeader">
        <div style="display: flex; justify-content: center; align-items: center; padding: 20px;">
          <h1 v-if="!isEditing">{{ paperHeader.paper_title }}</h1>
          <input v-if="isEditing" v-model="editableTitle" type="text" style="font-size: 24px; padding: 5px;" />
          <!-- 切换编辑模式按钮 -->
          <img style="width:20px;margin-bottom:-10px;padding:10px; cursor: pointer;" 
               src="@/assets/picture/exit.png" 
               alt="Exit" 
               @click="toggleEditTitle" 
               class="exit-button" />
        </div>
        <div class="paper-info">
          <span class="difficulty">难度: {{ paperHeader.difficulty === 1 ? '简单' : paperHeader.difficulty === 2 ? '中等' : '困难' }}</span>
          <span class="duration">时长: {{ paperHeader.during_time }} 分钟</span>
          <span class="direction">方向: {{ paperHeader.direction_title }}</span>
        </div>
      </header>
    </div>

    <div style="display: flex;height: 90vh;overflow: scroll;">
      <!-- 左侧题目列表 -->
      <aside class="question-list">
         <div class="list-header">
          
        </div>
        
        <!-- 试卷须知按钮，样式与其他题型一致 -->
        <div class="paper-notice" @click="selectQuestion({id: 'paperNotice'})">
          <span>试卷须知</span>
          <img 
            src="@/assets/picture/trash.png"
            class="trash-icon"
            @click="toggleBatchDeleteMode"
            :title="isBatchDeleteMode ? '点击确认删除' : '批量删除'"
          />
        </div>

        <!-- 遍历 questionGroups 并确保每个 group.questions 都是有效数组 -->
        <div v-if="questionGroups.length > 0">
          <div v-for="(group, groupIndex) in questionGroups" :key="groupIndex" class="question-group">
             <div class="group-header">
      
            <div v-if="group && Array.isArray(group.questions) && group.questions.length > 0">
              <input 
        v-if="isBatchDeleteMode"
        type="checkbox" 
        v-model="group.selected"
        @change="toggleGroupSelection(group)"
      />
      <span>{{ group.title }}（{{ group.questions.length }}小题，共{{ group.totalScore }}分）</span>
            </div>
            </div>
            <ul v-if="Array.isArray(group.questions)">
              <li 
                v-for="(question, questionIndex) in group.questions" 
                :key="question.id" 
                :class="{ 'active-question': currentQuestionId === question.id }" 
                @click="selectQuestion(question)"
              >
               <input 
                  v-if="isBatchDeleteMode"
                  type="checkbox" 
                  v-model="selectedQuestionIds"
                  :value="question.id"
                  @click.stop
                />
                <span>{{ groupIndex + 1 }}.{{ questionIndex + 1 }}. {{ question.title.replace(/<[^>]*>?/gm, '') }}</span>
                <span>{{ question.score }}分</span>
              </li>
            </ul>
          </div>
        </div>
        <div v-else>加载中...</div>
      </aside>

      <!-- 右侧试题编辑区域 -->
      <main class="question-editor">
        <div style="padding:20px 40px;height: 80%;overflow-y: scroll;">
          <div v-if="selectedQuestion && selectedQuestion.id === 'paperNotice'">
            <!-- 显示试卷须知 -->
            <div style="display: flex; justify-content: space-between; align-items: center;">
              <h3>试卷须知</h3>
              <!-- 编辑按钮，添加到试卷须知右侧 -->
              <img 
                src="@/assets/picture/exit_blue.png" 
                alt="Edit" 
                @click="toggleEditPaperNotice" 
                class="exit-button" 
                style="cursor: pointer; width: 20px;" 
              />
            </div>
            <div v-if="isEditingNotice">
              <QuillEditor v-model="editablePaperContent" />
              <button class="save-button" @click="savePaperNotice">保存试卷须知</button>
            </div>
            <p v-else style="font-size:18px;margin-left:40px" v-html="paperContent"></p>
          </div>

          <div v-if="selectedQuestion && selectedQuestion.id !== 'paperNotice'">
            <!-- 显示选择的题目 -->
            <div class="question-details">
              <div style="display: flex; justify-content: space-between; align-items: center;">
                <h4>{{ getQuestionTypeTitle(selectedQuestion.type) }} - {{ currentQuestionIndex }}</h4>
                 <!-- 编辑分值 -->
                <div style="display: flex; flex-direction:row;align-items: center;">
                  <div class="edit-score">
                    <label>分值：</label>
                    <input  v-if="selectedQuestion.isEditing" type="number" v-model="selectedQuestion.score" @change="updateScore(selectedQuestion)" />
                    <span v-else>{{ selectedQuestion.score }}分</span>
                  </div>
                  <!-- 编辑按钮，同行显示 -->
                  <img 
                    src="@/assets/picture/exit_blue.png" 
                    alt="Edit" 
                    @click="toggleEditQuestion(selectedQuestion)" 
                    class="exit-button" 
                    style="cursor: pointer; width: 20px;" 
                  />
                </div>
              </div>
              <div style="margin-left:40px">
                <!-- 题目标题编辑 -->
                <QuillEditor v-if="selectedQuestion.isEditing" v-model="selectedQuestion.title" />
                <p v-else v-html="selectedQuestion.title" style="margin-bottom: 15px; font-size:18px"></p>
                <!-- 选项编辑 -->
                <div v-if="selectedQuestion.type !== 'qna'" class="options">
                  <div v-for="(option, index) in selectedQuestion.options" :key="index" class="option">
                    <label>
                       <!-- 单选题和判断题：使用 radio -->
                      <input 
                        v-if="(selectedQuestion.type === 'only_sel' || selectedQuestion.type === 'yesorno') && selectedQuestion.isEditing"
                        type="radio" 
                        :name="'option' + selectedQuestion.id" 
                        :checked="option.correct" 
                        @change="updateOption(index, { text: option.text, correct: true })" 
                      />

                      <!-- 多选题：使用 checkbox -->
                      <input 
                        v-if="selectedQuestion.type === 'many_sel' && selectedQuestion.isEditing"
                        type="checkbox" 
                        :checked="option.correct" 
                        @change="updateOption(index, { text: option.text, correct: $event.target.checked })"
                      />
                      <!-- 文本框编辑 -->
                      <input 
                        v-if="selectedQuestion.isEditing" 
                        v-model="option.text" 
                        type="text" 
                        style="margin-left: 5px;border: none;height: 20px;width: 400px;" 
                        @change="updateOption(index, { text: option.text, correct: option.correct })" 
                      />
                      <span v-else>{{ String.fromCharCode(65 + index) }}. {{ option.text }}</span>
                    </label>
                    <!-- 删除选项按钮 - 判断题不允许删除选项 -->
                    <button  v-if="selectedQuestion.isEditing && selectedQuestion.type !== 'yesorno'"
                            style="width: 25px;border: none;height: 25px;background: none;"
                            type="button"
                            @click="removeOption(index)"
                            class="option-button"
                            title="删除选项"
                          >
                            <img style="width:25px;border:none;height:25px;"
                                src="@/assets/picture/delete.png" alt="删除" />
                    </button>
                    <span v-if="!selectedQuestion.isEditing && option.correct" class="correct-answer">正确答案</span>
                  </div>
                  <!-- 添加新选项 - 判断题不允许添加新选项 -->
                  <button class="save-button" v-if="selectedQuestion.isEditing && selectedQuestion.type !== 'yesorno'" @click="addOption">添加选项</button>
                </div>
                <!-- 简答题答案编辑 -->
                <div v-else class="answer-section">
                  <h4>标准答案:</h4>
                  <QuillEditor v-if="selectedQuestion.isEditing" v-model="selectedQuestion.answer" />
                  <p v-else v-html="selectedQuestion.answer"></p>
                </div>
              </div>
            </div>
          </div>

          <div v-else>
            <!-- 如果没有选中题目且没有试卷须知，显示空白图片 -->
            <img src="@/assets/picture/blank.png" alt="No question available" />
          </div>
        </div>

        <footer class="bottom-toolbar">
          <div class="toolbar-left">
            <div class="question-type-buttons">
              <button v-for="button in questionTypeButtons" :key="button.type" @click="selectQuestionType(button.type)">
                {{ button.label }}
              </button>
            </div>
          </div>
          <div class="toolbar-right">
            <button class="save-button" @click="saveExam">保存试卷</button>
          </div>
        </footer>
      </main>
    </div>
    <!-- 弹窗组件 -->
    <div v-if="showQuestionBankPage" class="modal-overlay" @click.self="closeQuestionBankPage">
      <div class="modal-content">
        <T_QuestionBankPage
          :isPopupMode="true"
          @selectQuestions="handleSelectedQuestions"
          @close="closeQuestionBankPage"
        />
      </div>
    </div>
  </div>
</template>



<script>
import { ref, onMounted } from 'vue';
import { useRoute,useRouter } from 'vue-router';
import QuillEditor from '@/components/QuillEditor.vue'; // 引入 QuillEditor 组件
import { deletePaperQuestion,getPaperDetails, getPaperHeader,updatePaperHeader, updateQuestionScore,updateQuestionDetail,addQuestionsToPaper,addQuestionToBackend } from '@/services/api';
import T_QuestionBankPage from '@/pages/teacher/T_QuestionBankPage.vue'; // 引入题库弹窗组件
import { ElMessage, ElMessageBox } from 'element-plus';
export default {
   components: {
    QuillEditor, // 注册 QuillEditor 组件
      T_QuestionBankPage, // 注册题库弹窗组件
  },
   props: {
    paperId: [String, Number], // 确保接收 paperId
     showPaperHeader: { // 新增 showPaperHeader prop
      type: Boolean,
      default: true  // 默认显示试卷头部
    }
  },
  setup() {
    const router = useRouter(); 
    const route = useRoute();
    const paperId = ref( route.params.paperId || localStorage.getItem('currentPaperId'));
    const currentQuestionId = ref(null);
    const currentQuestionIndex = ref(null); // 当前题目编号
    const selectedQuestion = ref(null);
    const questionGroups = ref([]);  // 问题组数据
    const paperHeader = ref(null);  // 试卷头数据
    const paperContent = ref(''); // 试卷须知内容
    const isEditing = ref(false); // 控制标题是否可编辑
    const editableTitle = ref(''); // 用来保存编辑的标题
    const addOptions = ref([]);  // 存放新增选项
    const updateOptions = ref([]);  // 存放更新选项
    const deleteOptions = ref([]);  // 存放删除选项
    const isEditingNotice = ref(false); // 控制试卷须知是否可编辑
    const editablePaperContent = ref(''); // 用来保存编辑的试卷须知内容
    const showQuestionBankPage = ref(false); // 控制题库页弹窗的显示与隐藏
    const selectedQuestionIds = ref([]);
    const isBatchDeleteMode = ref(false);
    const source = ref(route.query.source || 'default'); 
    const examId = route.query.examId;
    const semesterId = route.query.semesterId;

     const toggleGroupSelection = (group) => {
  const allSelected = group.questions.every(q => selectedQuestionIds.value.includes(q.id));
  
  if (allSelected) {
    selectedQuestionIds.value = selectedQuestionIds.value.filter(id => 
      !group.questions.some(q => q.id === id)
    );
  } else {
    const newSelected = group.questions
      .filter(q => !selectedQuestionIds.value.includes(q.id))
      .map(q => q.id);
    selectedQuestionIds.value = [...selectedQuestionIds.value, ...newSelected];
  }
  group.selected = !allSelected;
};

const toggleBatchDeleteMode = () => {
  if (isBatchDeleteMode.value) {
    // 已经是删除模式时，如果有选中项则执行删除，否则直接退出
    if (selectedQuestionIds.value.length > 0) {
      handleBatchDelete();
    } else {
      isBatchDeleteMode.value = false;
    }
  } else {
    // 进入批量删除模式
    isBatchDeleteMode.value = true;
    selectedQuestionIds.value = [];
  }
};
const handleBatchDelete = async () => {
  try {
    if (selectedQuestionIds.value.length === 0) {
      isBatchDeleteMode.value = false;
      return;
    }

    await ElMessageBox.confirm(
      `确定删除选中的 ${selectedQuestionIds.value.length} 道题目吗？`,
      '警告',
      {
        confirmButtonText: '删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );

    const paperQsIds = questionGroups.value
      .flatMap(group => group.questions)
      .filter(q => selectedQuestionIds.value.includes(q.id))
      .map(q => q.paper_qs_id)
      .join(',');

    await deletePaperQuestion(paperQsIds);
    
    questionGroups.value = questionGroups.value.map(group => ({
      ...group,
      questions: group.questions.filter(q => !selectedQuestionIds.value.includes(q.id))
    }));
    
    ElMessage.success('删除成功');
    
  } catch (error) {
    // 用户取消操作自动捕获
  } finally {
    isBatchDeleteMode.value = false;
    selectedQuestionIds.value = [];
  }
};

   // 显示题库页弹窗
    const showQuestionBank = () => {
      showQuestionBankPage.value = true;
    };

    // 关闭题库页弹窗
    const closeQuestionBankPage = () => {
      showQuestionBankPage.value = false;
    };

       // 处理从题库页选择的题目
const handleSelectedQuestions = async (selectedQuestions) => {
  if (selectedQuestions.length === 0) {
    ElMessage.w("请先选择题目！");
    return;
  }

  // 构建请求体
  const techId = parseInt(localStorage.getItem('id'), 10); // 确保 tech_id 是数字
  const requestBody = {
    tech_id: techId,
    paper_id: parseInt(paperId.value, 10), // 确保 paper_id 是数字
    qs_ids: [...selectedQuestions] // 确保 qs_ids 是一个标准数组
  };

  console.log('Request body:', requestBody);

  try {
    // 使用 addQuestionsToPaper 进行请求
    const response = await addQuestionsToPaper(requestBody);
    console.log('API Response:', response);

    if (response.data.status === 1) {
      ElMessage.success('题目成功添加到试卷中');
      await fetchPaperDetails();
    } else {
      console.error('添加题目失败:', response.data.msg);
      ElMessage.error('添加题目失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败:', error);
    ElMessage.error('请求失败，请重试');
  }

  closeQuestionBankPage();
};


// 新增题目时保存到后端
const addNewQuestion = async (question) => {
  // 构造新增题目的请求数据
  const requestBody = {
    tech_id: parseInt(localStorage.getItem('id'), 10) || 0,  // 获取老师ID
    paper_id: parseInt(paperId.value, 10) || 0,  // 试卷ID
    qs_title: question.title || '',  // 题目描述
    qs_type: question.type || 'only_sel',  // 题目类型，默认为单选题
    max_score: question.score || 0,  // 题目满分
    difficulty: question.difficulty || 1,  // 难度等级，默认为1
    direction_id: paperHeader.value.direction_id || 0,  // 方向ID
    options: question.options.map(option => ({
      option_content: option.text || '',  // 选项内容，默认为空字符串
      is_right: option.correct ? 1 : 0,  // 是否正确答案，默认为0（false）
    })),
    right_ans: question.type === 'qna' ? question.answer || '' : null,  // 如果是简答题，包含标准答案
  };

  try {
    const response = await addQuestionToBackend(requestBody);
    if (response.status === 200 && response.data.status === 1) {
      ElMessage.success('题目添加成功!');
      await fetchPaperDetails();  // 重新获取试卷内容，确保新题目显示出来
      return response.data.data.qs_id;  // 返回新生成的题目 ID
    } else {
      console.error('添加失败: ', response.data.msg);
      throw new Error('添加失败: ' + response.data.msg);
    }
  } catch (error) {
    console.error('请求失败: ', error);
    throw error;  // 抛出错误，以便在调用方捕获
  }
};

 

     const toggleEditPaperNotice = () => {
      if (isEditingNotice.value) {
        editablePaperContent.value = paperContent.value; // 当进入编辑模式时，设置为当前的内容
      }
      isEditingNotice.value = !isEditingNotice.value;
    };

    // 保存编辑后的试卷须知
    const savePaperNotice = async () => {
      paperContent.value = editablePaperContent.value; // 更新试卷须知内容

      const updatedHeader = {
        paper_id: paperId.value,
        direction_id: paperHeader.value.direction_id,
        paper_title: paperHeader.value.paper_title,
        paper_content: paperContent.value, // 使用编辑后的试卷内容
        during_time: paperHeader.value.during_time,
        difficulty: paperHeader.value.difficulty,
      };

      try {
        const response = await updatePaperHeader(updatedHeader);
        if (response && response.status === 200 && response.data.status === 1) {
          ElMessage.success('试卷须知更新成功!');
          isEditingNotice.value = false; // 退出编辑模式
        } else {
          console.error('更新失败: ', response ? response.data.msg : '无响应数据');
          ElMessage.error('更新失败');
        }
      } catch (error) {
        console.error('请求失败: ', error);
        ElMessage.error('请求失败');
      }
    };


// 新增选项时
const addOption = () => {
  if (selectedQuestion.value.type === 'yesorno') return; // 判断题不允许增加选项

  const newOption = { text: '', correct: false, option_id: null }; // 默认不选中
  if (selectedQuestion.value.type === 'only_sel') {
    // 单选题：新增选项时，确保只有一个选项为正确答案
    selectedQuestion.value.options.forEach(option => (option.correct = false));
  }
  selectedQuestion.value.options.push(newOption);
  addOptions.value.push(newOption); // 保存到新增选项数组
};

// 删除选项时
const removeOption = (index) => {
  if (selectedQuestion.value.type === 'yesorno') return; // 判断题不允许删除选项

  const removedOption = selectedQuestion.value.options.splice(index, 1)[0];
  if (removedOption && removedOption.correct) {
    // 如果删除的是正确答案，重置正确答案状态
    if (selectedQuestion.value.type === 'only_sel') {
      selectedQuestion.value.options[0] && (selectedQuestion.value.options[0].correct = true);
    }
  }

  if (removedOption.option_id) {
    deleteOptions.value.push({ option_id: removedOption.option_id });
  }
};

// 更新选项时
const updateOption = (index, newOptionData) => {
  const option = selectedQuestion.value.options[index];

  if (option) {
    if (selectedQuestion.value.type === 'only_sel' || selectedQuestion.value.type === 'yesorno') {
      // 单选题和判断题：清除其他选项的正确答案，仅保留当前选中的为正确答案
      selectedQuestion.value.options.forEach((opt, i) => {
        opt.correct = i === index; // 仅当前选项为正确答案
      });
    } else if (selectedQuestion.value.type === 'many_sel') {
      // 多选题：切换选项的正确状态
      option.correct = newOptionData.correct;
    }

    // 更新选项文本内容（仅对非判断题和单选题适用）
    if (selectedQuestion.value.type !== 'yesorno') {
      option.text = newOptionData.text;
    }

    // 更新选项队列
    if (option.option_id) {
      const existingOption = updateOptions.value.find(opt => opt.option_id === option.option_id);
      if (existingOption) {
        // 更新已存在的选项
        existingOption.option_content = option.text;
        existingOption.is_right = option.correct;
      } else {
        // 添加新更新项
        updateOptions.value.push({
          option_id: option.option_id,
          option_content: option.text,
          is_right: option.correct,
        });
      }
    }
  }
};


// 保存题目时，确保正确提交数据
const saveQuestion = async (question) => {
   const updatedOptions = question.options.map((option) => ({
    option_id: option.option_id || null, // 如果是新选项，option_id 为空
    option_content: option.text,
    is_right: option.correct,
  }));
  // 创建更新数据
  const updatedQuestion = {
    qs_id: question.id,
    paper_id: paperId.value,
    max_score: question.score,
    question: {
      tech_id: localStorage.getItem('id'),
      qs_id: question.id,
      qs_title: question.title,
      qs_type: question.type,
      right_ans: question.type === 'qna' ? question.answer : null,
      options: addOptions.value.map(option => ({
        option_id: null,
        option_content: option.text,
        is_right: option.correct,
      })),
      update_options: updatedOptions, // 提交更新后的选项数据
      delete_options: deleteOptions.value.map(option => ({
        option_id: option.option_id,
      })),
      difficulty: question.difficulty,
      direction_id: paperHeader.value.direction_id,
    },
  };

  try {
    const response = await updateQuestionDetail(updatedQuestion);
    if (response.status === 200 && response.data.status === 1) {
      ElMessage.success('题目更新成功!');
    } else {
      ElMessage.error('更新失败');
    }
  } catch (error) {
    console.error('请求失败: ', error);
    ElMessage.error('请求失败');
  }
};


    // 处理点击空白区域的事件
    const handleClickOutside = (event) => {
      // 确保只有在编辑模式下且点击的区域不是输入框或标题编辑按钮时触发提交
      if (isEditing.value && !event.target.closest('.paper-header') && !event.target.closest('input')) {
        toggleEditTitle();
      }
    };

    // 题型选择按钮
    const questionTypeButtons = ref([
      { type: 'only_sel', label: '单选题' },
      { type: 'many_sel', label: '多选题' },
      { type: 'yesorno', label: '判断题' },
      { type: 'qna', label: '简答题' }
    ]);

    // 修改题目分数并更新 API
    const updateScore = async (question) => {
      const { id, score } = question; // 获取题目ID和分数
      try {
        // 调用更新分数的 API 方法
        const response = await updateQuestionScore(id, paperId.value, score);
        if (response.status === 200 && response.data.status === 1) {
         ElMessage.success('题目分数已更新成功!');
        } else {
          console.error('更新失败: ', response ? response.data.msg : '无响应数据');
          ElMessage.error('更新失败');
        }
      } catch (error) {
        console.error('请求失败: ', error);
        ElMessage.error('请求失败');
      }
    };

      // 切换题目编辑模式
   const toggleEditQuestion = (question) => {
  // 切换编辑模式
  question.isEditing = !question.isEditing;

  // 如果退出编辑模式，判断是新增题目还是已有题目进行保存
  if (!question.isEditing) {
    if (typeof question.id === 'string' && question.id.startsWith('new')) {
      addNewQuestion(question);  // 新增题目保存
    } else {
      saveQuestion(question);  // 已有题目更新保存
    }
  }
};


    // 选择题目并显示其内容
 const selectQuestion = (question) => {
  // 如果已经有问题在编辑模式，先关闭编辑模式
  if (selectedQuestion.value && selectedQuestion.value.isEditing) {
    selectedQuestion.value.isEditing = false;
  }

  if (question.id === 'paperNotice') {
    selectedQuestion.value = { id: 'paperNotice' };
  } else {
    currentQuestionId.value = question.id;
    currentQuestionIndex.value = getQuestionIndex(question);
    selectedQuestion.value = question;
    selectedQuestion.value.options = question.options || [];  // 确保选项数据正确传递
  }
};



    // 获取当前问题的索引
    const getQuestionIndex = (question) => {
      let questionIndex = null;
      questionGroups.value.forEach((group) => {
        const index = group.questions.findIndex(q => q.id === question.id);
        if (index !== -1) {
          questionIndex = index + 1; // 返回题目序号（1-based）
        }
      });
      return questionIndex;
    };

    // 获取题目类型标题
    const getQuestionTypeTitle = (type) => {
      const types = {
        only_sel: '一、【单选题】',
        many_sel: '二、【多选题】',
        yesorno: '三、【判断题】',
        qna: '四、【简答题】',
      };
      return types[type] || '未知题型';
    };

    // 保存试卷
    const saveExam = () => {
  ElMessage.success('试卷已保存');

  if (source.value === 'class') {
    // 如果来源是从第一个页面
    console.log(source)
    localStorage.setItem('currentPaperId', paperId.value);
    localStorage.setItem('currentExamId', examId);
    localStorage.setItem('currentSemesterId', semesterId);
            localStorage.setItem('currentExamStatus', 0);
        localStorage.setItem('currentExamTitle', paperHeader.value.paper_title);

    router.push({ name: 'ExamDetail', params: { examId, semesterId } });
  } else {
    console.log(source)
    router.push('/teacher/T_QA');
  }
};

    //创建新的题目
const selectQuestionType = (type) => {
  console.log('选择题目类型: ', type);

  const newQuestion = {
    id: `new-${Date.now()}`,  // 使用时间戳作为唯一ID
    title: '',  // 默认空标题
    score: 0,  // 默认分值为0
    options: [],
    type,
    isEditing: true,  // 新建的题目默认进入编辑模式
    difficulty: 1,  // 默认难度
    answer: type === 'qna' ? '' : null,  // 如果是简答题，则需要标准答案
  };

  // 初始化选项内容
  if (type === 'only_sel' || type === 'many_sel') {
    newQuestion.options = [{ text: '', correct: false }];  // 单选题和多选题至少有一个默认选项
  } else if (type === 'yesorno') {
    newQuestion.options = [
      { text: '正确', correct: false },
      { text: '错误', correct: false }
    ];  // 判断题只有正确和错误两个选项
  }

  // 设置当前选中的题目为新建的题目对象
  selectedQuestion.value = newQuestion;

  // 你可以将新建的题目对象加入到题目组中，或者保存到一个独立的状态
  questionGroups.value.push({
    title: getQuestionTypeTitle(type),
    totalScore: 0,
    questions: [newQuestion]
  });
};


    // 切换标题的编辑模式并更新标题
    const toggleEditTitle = async () => {
      if (isEditing.value) {
        paperHeader.value.paper_title = editableTitle.value;

        const updatedHeader = {
          paper_id: paperId.value,
          direction_id: paperHeader.value.direction_id,  // 方向 ID
          paper_title: paperHeader.value.paper_title,  // 使用编辑后的标题
          paper_content: paperHeader.value.paper_content,  // 试卷内容
          during_time: paperHeader.value.during_time,  // 试卷时长
          difficulty: paperHeader.value.difficulty,  // 难度
        };

        try {
          console.log('Sending request to update paper header:', updatedHeader); // 添加日志
          const response = await updatePaperHeader(updatedHeader);
          
          // 仅在有有效响应时处理
          if (response && response.status === 200 && response.data.status === 1) {
            ElMessage.success('试卷标题更新成功!');
          } else {
            console.error('更新失败: ', response ? response.data.msg : '无响应数据');
            ElMessage.error('更新失败');
          }
        } catch (error) {
          console.error('请求失败: ', error); // 打印请求错误
          ElMessage.error('请求失败');
        }
      } else {
        editableTitle.value = paperHeader.value.paper_title;
      }

      isEditing.value = !isEditing.value;
    };

   // 获取试卷头部数据
    const fetchPaperHeader = async () => {
      try {
        const response = await getPaperHeader(paperId.value);
        if (response.status === 200 && response.data.status === 1) {
          paperHeader.value = response.data.data;  // 设置试卷头部数据
          paperContent.value = response.data.data.paper_content;  // 设置试卷须知内容
        }
      } catch (error) {
        console.error('请求失败: ', error);
      }
    };

    // 获取试题数据
    const fetchPaperDetails = async () => {
      try {
        const response = await getPaperDetails(paperId.value);
        if (response.status === 200 && response.data.status === 1) {
          const paperData = response.data.data;
          questionGroups.value = paperData.paperList.map((group) => ({
            title: group.format_content,
            totalScore: group.format_score,
            questions: Array.isArray(group.items) ? group.items.map((item) => ({
              id: item.qs_id,
               paper_qs_id: item.paper_qs_id,// 新增paper_qs_id字段
              title: item.qs_title,
              score: item.q_score,
              options: item.options?.map((opt) => ({
                text: opt.option_content,
                correct: opt.is_right,
                 option_id: opt.option_id  // 确保获取选项的 option_id
              })) || [],
              type: item.qs_type,
              difficulty: item.difficulty,
              answer: item.qna_ans || null,
            })) : [],  // 确保 questions 永远是数组
          }));
        } else {
          console.error('获取试题失败: ', response.data.msg);
        }
      } catch (error) {
        console.error('请求失败: ', error);
      }
    };

    onMounted(() => {
      fetchPaperHeader();
      fetchPaperDetails();
      selectedQuestion.value = { id: 'paperNotice' }; // 默认选中试卷须知
    });

    return {
      paperHeader,
      questionGroups,
      selectedQuestion,
      currentQuestionId,
      currentQuestionIndex,
      questionTypeButtons,
      selectQuestion,
      saveExam,
      selectQuestionType,
      paperContent,
      getQuestionTypeTitle,  // 确保将方法暴露给模板
      isEditing,
      editableTitle,
      toggleEditTitle,
      updatePaperHeader,
      handleClickOutside, 
      updateScore,
      toggleEditQuestion,
      saveQuestion,
      addOption,
      removeOption,
      updateOption,
       isEditingNotice,
      editablePaperContent,
      toggleEditPaperNotice,
      savePaperNotice,
       showQuestionBankPage,
      showQuestionBank,
      closeQuestionBankPage,
      handleSelectedQuestions,
      addNewQuestion,
      selectedQuestionIds,
      handleBatchDelete,
  isBatchDeleteMode,
  toggleGroupSelection,
   toggleBatchDeleteMode,

    };
  }
};
</script>


<style scoped>
.list-header {
  display: flex;
  gap: 10px;
  padding: 10px;
  justify-content: space-between;
}

.trash-icon {
  width: 24px;
  height: 24px;
  cursor: pointer;
}

.batch-delete-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
}
.quill-editor {
  height: 200px; /* 可以根据实际需求调整高度 */
  margin-bottom: 15px; /* 增加底部边距，防止与下方内容贴得太紧 */
}

.paper-notice {
  padding: 12px;
  cursor: pointer;
  background-color: #f7f9fc;
  border-radius: 8px;
  font-size: 14px;
  margin-bottom: 15px;
  transition: background 0.3s, color 0.3s;
  font-weight: bold;
  color: #4a4a4a;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.paper-notice:hover {
  background-color: #dae7ff;
  color: #2f80ed;
}
/* Enhanced Styles for Improved Aesthetic */
.exam-editor-container {
  display: flex;
  flex-direction: column;
  background-color: #f5f6fa;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}

/* Left Sidebar - Question List Styles */
.question-list {
  width: 25%;
  background: #ffffff;
  padding: 20px;
  border-right: 1px solid #dfe4ea;
  overflow-y: auto;
  box-shadow: 2px 0 5px rgba(0, 0, 0, 0.1);
}

.back-button {
  background: none;
  border: none;
  color: #2f80ed;
  font-size: 16px;
  cursor: pointer;
  font-weight: bold;
  margin-bottom: 20px;
}
.exit-button:hover {
  opacity: 0.7; /* 鼠标悬停时添加轻微透明效果 */
  
}

.question-group {
  margin-bottom: 20px;
}

.group-header {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.question-group ul {
  list-style: none;
  padding: 0;
}

.question-group li {
  padding: 12px;
  cursor: pointer;
  transition: background 0.3s, box-shadow 0.3s;
  border-radius: 8px;
  margin-bottom: 8px;
  background-color: #f9f9f9;
}
.question-group li {
  display: flex; /* 添加 flex 布局 */
  justify-content: space-between; /* 使内容两端对齐 */
  align-items: center; /* 垂直居中 */
  padding: 12px;
  cursor: pointer;
  transition: background 0.3s, box-shadow 0.3s;
  border-radius: 8px;
  margin-bottom: 8px;
  background-color: #f9f9f9;
}

.question-group li span:first-child {
  flex: 1; /* 左侧文字部分占用剩余空间 */
  white-space: nowrap; /* 防止文字换行 */
  overflow: hidden; /* 防止文字超出 */
  text-overflow: ellipsis; /* 文字超出部分显示省略号 */
}

.question-group li span:last-child {
  margin-left: auto; /* 推动分数值到最右 */
  font-weight: bold;
  color: #333; /* 可根据需要调整颜色 */
}
.active-question {
  background-color: #F0F4F8;
  border:1px solid rgba(47, 128, 237, 0.3);
}

.question-group li:hover {
  background-color: #f0f4f8;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
}

/* Right Panel - Question Editor Styles */
.question-editor {
  flex: 1;
  background: #ffffff;
  border-left: 1px solid #dfe4ea;
}

.option {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #e3e6ea;
  border-radius: 6px;
}

.option:hover{
  background-color: #f7f9fc;
}
.correct-answer {
  color: #27ae60;
  font-weight: bold;
}

.edit-score {
  margin-right: 20px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.edit-score label {
  font-weight: bold;
}

.edit-score input[type="number"] {
  width: 80px;
  padding: 8px;
  border: 1px solid #d0d0d0;
  border-radius: 2px;
  font-size: 14px;
  transition: border-color 0.3s, box-shadow 0.3s;
  margin-right: 20px;
}
/* Footer Toolbar Styles */
.bottom-toolbar {
  padding: 10px 20px;
  background-color: #ffffff;
  border-top: 1px solid #ddd;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0px -2px 5px rgba(0, 0, 0, 0.1);
  position: sticky;
  bottom: 0;
  top: 90vh;
}

.toolbar-left {
  display: flex;
  align-items: center;
  gap: 15px;
}


.question-type-buttons {
  display: flex;
  gap: 15px;
}

.question-type-buttons button {
  padding: 10px 16px;
  border: 1px solid #d0d0d0;
  cursor: pointer;
  background-color: #ffffff;
  border-radius: 6px;
  transition: background 0.3s, box-shadow 0.3s, color 0.3s;
  font-weight: bold;
  color: #4a4a4a;
}

.question-type-buttons button:hover {
  background-color: #dae7ff;
  border-color: #2f80ed;
  color: #2f80ed;
  box-shadow: 0px 0px 8px rgba(47, 128, 237, 0.3);
}

/* Save Button Styles */
.toolbar-right {
  display: flex;
  align-items: center;
}

.save-button {
  padding: 10px 20px;
  background-color: #2f80ed;
  color: #ffffff;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: bold;
  font-size: 15px;
  transition: background 0.3s, box-shadow 0.3s;
}

.save-button:hover {
  background-color: #4a90e2;
  box-shadow: 0px 4px 12px rgba(47, 128, 237, 0.3);
}

/* Scrollbar Styles */
.question-list::-webkit-scrollbar {
  width: 8px;
}

.question-list::-webkit-scrollbar-thumb {
  background-color: #c4c4c4;
  border-radius: 4px;
}

.question-list::-webkit-scrollbar-thumb:hover {
  background-color: #a6a6a6;
}

/* Responsive Improvements */
@media (max-width: 768px) {
  .exam-editor-container {
    flex-direction: column;
  }

  .question-list {
    width: 100%;
    height: 40vh;
  }

  .question-editor {
    height: 60vh;
  }

  .bottom-toolbar {
    flex-direction: column;
    gap: 10px;
  }
}

@media (max-width: 480px) {
  .save-button {
    padding: 8px 16px;
    font-size: 14px;
  }

  .question-type-buttons button {
    padding: 8px 10px;
    font-size: 13px;
  }
}
/* 试卷头样式 */
.paper-header {
  background-color: #2f80ed;
  color: #ffffff;
  padding: 20px;
  text-align: center;
}

.paper-header h1 {
  font-size: 24px;
  margin-bottom: 10px;
  font-weight: bold;
}

.paper-info {
  display: flex;
  justify-content: center;
  gap: 20px;
  font-size: 16px;
}

.paper-info span {
  padding: 5px 10px;
  background-color: #ffffff;
  color: #2f80ed;
  border-radius: 8px;
  font-weight: bold;
}

.difficulty {
  background-color: #f7f7f7;
  color: #27ae60;
}

.duration {
  background-color: #f7f7f7;
  color: #f39c12;
}
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000; /* 确保弹窗在最前面 */
}

.modal-content {
  background: white;
  padding: 20px;
  border-radius: 8px;
  width: 80%;
  max-height: 85vh;
  overflow-y: auto;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}
</style>